package com.aws.remote;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2024/1/17 - 16:21
 */
@Component
public class RemoteDemo2 {
    @Autowired
    AmazonS3 s3Client;


    public void test(){
        String bucketName = "mylibugu";
        String localFolderPath = "C:\\Users\\libugu\\Desktop\\2027";
        String prefix = "12";

        TransferManager transferManager = new TransferManager(s3Client);

        try {
            File localFolder = new File(localFolderPath);
            if(!localFolder.isDirectory()) {
                throw new AmazonClientException("Local path is not a folder");
            }

            for (File file : localFolder.listFiles()) {
                if (file.isDirectory() && file.getName().startsWith(prefix)) {
                    uploadDirectory(transferManager, s3Client, bucketName, "/Users/2027", file.getAbsolutePath(), file.getName());
                } else if (file.isFile() && file.getName().startsWith(prefix)) {
                    Upload upload = transferManager.upload(bucketName, "/Users/2027" + "/" + file.getName(), file);
                    upload.waitForCompletion();
                }
            }
        } catch (AmazonClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            transferManager.shutdownNow();
        }
    }
    public static void uploadDirectory(TransferManager transferManager, AmazonS3 s3Client, String existingBucketName, String bucketSubdirectory, String localDirectoryPath, String directoryName) throws InterruptedException {
        File dir = new File(localDirectoryPath);
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                uploadDirectory(transferManager, s3Client, existingBucketName, bucketSubdirectory + "/" + directoryName, file.getAbsolutePath(), file.getName());
            } else {
                Upload upload = transferManager.upload(existingBucketName, bucketSubdirectory + "/" + directoryName + "/" + file.getName(), file);
                upload.waitForCompletion();
            }
        }
    }
}
